package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.BaseContext;
import com.reggie.dao.*;
import com.reggie.pojo.*;
import com.reggie.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements IOrdersService {
    @Autowired
    private ShoppingCartDao shoppingCartDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AddressBookDao addressBookDao;
    @Autowired
    private OrderDetailDao orderDetailDao;

    /*
    * 提交订单(模拟支付) 找出相对应的数据添加到orders和orders_detail中
    * 1.orders表加一条数据 清空代码只留打印orders,发现只有
    *   id,number,status,user_id,address_book_id,order_time,checkout_time,pay_method
    *   amount,remark,phone,address,user_name,consignee
    * 2.orders_detail表 从shoppingCart复制属性 修改amount 添加order_id
    *   id,name,image,order_id,dish_id,setmeal_id,dish_flavor,number,amount
    * 3.shoppingCart表清空数据
    * */
    @Override
    public void submit(Orders orders) {
        log.info(orders.toString());

        // 0、获取用户id
        Long userId = BaseContext.getCurrentId();
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
        sclqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartDao.selectList(sclqw);

        // 2、查询用户数据 select * from user where id = ?
        User user = userDao.selectById(userId);
        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        AddressBook addressBook = addressBookDao.selectById(orders.getAddressBookId());

        //idworker 是一个基于zookeeper和snowflake算法的分布式统一ID生成工具
        long orderId = IdWorker.getId();
        //解决雪花算法datacenterId重复问题

        //order的amount，支付总金额
        BigDecimal amount = new BigDecimal(0);

        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //要添加的(多行)数据 行数 = 购物车几条数据
            OrderDetail orderDetail = new OrderDetail();
            //复制购物车数据到订单详情
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //每道菜的单价
            BigDecimal price = shoppingCart.getAmount();
            //number是Integer类型,要用到BigDecimal的运算，类型转换
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            //订单详情的金额 价格*单价 orderDetail.amount = shoppingCart.amount * shoppingCart.number
            //修改复制过来的amount数据
//            BigDecimal multiply = price.multiply(number);
//            log.info(multiply.toString());

            orderDetail.setAmount(price.multiply(number));

            //订单详情加一个金额 订单就加一个 得出总金额
            amount = amount.add(orderDetail.getAmount());
            //amount = amount + orderDetail.getAmount()
            //单独设置 比购物车多的属性 orderId
            orderDetail.setOrderId(orderId);
            orderDetailDao.insert(orderDetail);
        }

        // 5、保存订单数据，有许多数据需要单独设置
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserId(userId);
        orders.setStatus(2);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "": addressBook.getProvinceName())+
                (addressBook.getCityName() == null ? "" : addressBook.getCityName())+
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())+
                addressBook.getDetail());
        orders.setAmount(amount);
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());

        this.save(orders);
        // 6、删除当前用户的购物车数据
        shoppingCartDao.delete(sclqw);

    }
}
